package com.szgr.baoyin.fragment;


import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.szgr.baoyin.MyApplication;
import com.szgr.baoyin.R;
import com.szgr.baoyin.adapter.PersonalOrderListAdapter;
import com.szgr.baoyin.model.OrderInfo;
import com.szgr.baoyin.myview.NoScrollListView;
import com.szgr.baoyin.utils.Constant;
import com.szgr.baoyin.utils.DialogUtils;
import com.szgr.baoyin.utils.ToastUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * A simple {@link Fragment} subclass.
 */
public class PersonalOrderFragment extends Fragment implements View.OnClickListener {


    private List<OrderInfo> data;
    private PersonalOrderListAdapter orderListAdapter;
    private TextView tv_record;

    public PersonalOrderFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View ret = inflater.inflate(R.layout.fragment_personal_order, container, false);
        initView(ret);
        return ret;
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    private void initView(View ret) {
        data = new ArrayList<>();
        NoScrollListView orderListView = (NoScrollListView) ret.findViewById(R.id.personal_order_list_view);
        orderListAdapter = new PersonalOrderListAdapter(getActivity(), data ,this);
        orderListView.setAdapter(orderListAdapter);

        tv_record = (TextView) ret.findViewById(R.id.order_no_record);

        if(MyApplication.getmInstance().isLogin()) {
            getOrder();
        }
    }

    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case Constant.REQUEST_SUCCESS:
                    tv_record.setVisibility(View.GONE);
                    break;
                case Constant.REQUEST_FAIL:
                    tv_record.setVisibility(View.VISIBLE);
                    break;
                case 1008:
                    ToastUtils.showToast("获取订单失败");
                    break;
                case 506:
                    getOrder();
                    break;
            }
            DialogUtils.hideLoadingDialog();
        }
    };

    private void getOrder() {
        DialogUtils.showLoadingDialog(getActivity(), "正在拼命加载中...", false);
        StringRequest sr = new StringRequest(Request.Method.POST, Constant.URL_ORDER_LIST,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                            System.out.println("-----order list----->" + s);
                            try {
                                JSONObject jsonObject = new JSONObject(s);
                                if(jsonObject.has("datas")){
                                    JSONObject datas = jsonObject.getJSONObject("datas");
                                    if(datas.has("order_group_list")){
                                        JSONArray order_group_list = datas.getJSONArray("order_group_list");
                                        Gson gson = new Gson();
                                        data = gson.fromJson(order_group_list.toString(),new TypeToken<List<OrderInfo>>(){}.getType());
                                        if(data.size() == 0){
                                            mHandler.obtainMessage(Constant.REQUEST_FAIL).sendToTarget();
                                        }else{
                                            mHandler.obtainMessage(Constant.REQUEST_SUCCESS).sendToTarget();
                                        }
                                        orderListAdapter.setData(data);
                                    }
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                mHandler.sendEmptyMessage(1008);
            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> map = new HashMap<>();
                map.put("key",MyApplication.getmInstance().getKey());
                map.put("order_state","20");
                return map;
            }
        };
        MyApplication.getmInstance().addToRequestQueue(sr);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.message_order_confirm:
                int tag = (int) v.getTag();
                OrderInfo orderInfo = data.get(tag);
                OrderInfo.MyOrderItem myOrderItem = orderInfo.getOrder_list().get(0);
                confirmOrder(myOrderItem.getOrder_id());
                break;
            case R.id.message_order_connect:
                Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + Constant.PHONE));
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
                break;
        }
    }

    private void confirmOrder(final String orderId) {
        StringRequest sr = new StringRequest(Request.Method.POST, Constant.URL_ORDER_CONFIRM,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        System.out.println("---order--->" + s);
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            String datas = jsonObject.getString("datas");
                            if("1".equals(datas)){
                                mHandler.obtainMessage(506).sendToTarget();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> map = new HashMap<>();
                map.put("key",MyApplication.getmInstance().getKey());
                map.put("order_id",orderId);
                return map;
            }
        };
        MyApplication.getmInstance().addToRequestQueue(sr);
    }
}
